<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;

class UserChangeShop extends Model
{
	
	// ----------------
	// ---模型事件---
	//----------------
	protected static function init()
	{
    	//插入或更新后-发送通知
    	self::event('after_write', function ($data) {
    		$title  = '申请处理通知';
        	switch($data->status ?? 0){
			    case 0: //申请成功
			    	model('msg')->send(0,0,$title,"有新的变更店铺申请，请注意查收！");
			        break;
			    case 1: //审核通过
			    	$msg = "您申请变更店铺,已通过审核！";
			    	model('msg')->send(0,$data['uid'],$title,$msg);
			        break;    
			    case -1://审核不通过
			    	$msg = "您申请变更店铺,已被驳回！";
			    	model('msg')->send(0,$data['uid'],$title, $msg.($data->status_desc) );
			       break;            
			}
        });
    }
	
	/**
     * 添加变更申请
     * @param type $phone
     * @return type
     */
	public function addApply($uid,$this_shop_id,$shop_id)
    {
    	if( !model('shop')->get($shop_id) ){
    		throw new \think\Exception("店铺不存在！");
    	}
    	if( self::where('uid',$uid)->where('status',0)->find() ){
    		throw new \think\Exception("当前存在申请中变更记录还未处理！");
    	}
    	self::save(['uid'=>$uid,'shop_id'=>$this_shop_id,'change_shop_id'=>$shop_id]);
    	return $this;
    }
	
	
	 /**
     * 变更店铺
     * @param type $phone
     * @return type
     */
	public function changeShop($id)
    {
    	$apply = self::where('status',0)->get($id);
		if( !$apply ){
			throw new \think\Exception("找不到该申请记录");
		}
		
		$user = model('user')->get($apply->uid);
		
		//赠送余额  积分  佣金   订单
		$backup['integral'] = $user ->integral;
		$backup['brokerage'] = $user ->brokerage;
		$backup['balance_gift'] = $user ->balance_gift;
		
		$user ->integral = 0;
		//$user ->brokerage = 0;
		$user ->balance_gift = 0;
		$user ->shop_id = $apply->change_shop_id;
		if( !$user->save() ){
			throw new \think\Exception("异常错误！");
		}
		
		//保存
		$apply->backup = $backup;
		$apply->status = 1;
		$apply->status_time = date('Y-m-d H:i:s');
		$apply->update_user = request() ->userInfo['user_name'];
		return $apply->save();
    }
 
    /**
     * 驳回
     * @param type $uid
     * @return type
     */
	public function reject($id,$desc)
    {
		if( !$apply = self::where('status',0)->get($id) ){
			throw new \think\Exception("找不到该申请记录");
		}
		$apply->status = -1;
		$apply->status_desc = $desc;
		$apply->status_time = date('Y-m-d H:i:s');
		$apply->update_user = request() ->userInfo['user_name'];
		$apply->save();
    }
    
}
